package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.mapper.MenuMapper;
import cn.wolfcode.crm.query.MenuQuery;
import cn.wolfcode.crm.service.IMenuService;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

@Service
public class MenuServiceImpl implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;

    public void saveOrUpdate(Menu entity) {
        if (entity.getId() == null) {
            menuMapper.insert(entity);
        } else {
            menuMapper.updateByPrimaryKey(entity);
        }
    }

    public void delete(Long id) {
        //先删除子菜单
        menuMapper.deleteChildByParentId(id);

        //再删除父菜单
        menuMapper.deleteByPrimaryKey(id);
    }

    public Menu get(Long id) {
        return menuMapper.selectByPrimaryKey(id);
    }

    public List<Menu> listAll() {
        return menuMapper.selectAll();
    }

    @Override
    public List<Menu> selectRootMenu() {
        return menuMapper.selectRootMenu();
    }

    @Override
    public List<Long> selectByRoleId(Long id) {
        return menuMapper.selectByRoleId(id);
    }

    @Override
    public List<Menu> selectEmployeeMenu() {
        // 获取 所有 菜单
        List<Menu> menus = menuMapper.selectRootMenu();
        // 获取 当前 用户
        Employee emp = UserContext.getCurrentUser();
        // 管理员
        if (emp.isAdmin()) {
            return menus;
        }
        // 获取 当前用户的 所有菜单 id 集合
        List<Long> ids = menuMapper.selectByEmployeeId(emp.getId());
        checkPermission(menus, ids);
        return menus;
    }


    @Override
    public List<Menu> query(MenuQuery qo) {
        List<Menu> menus = menuMapper.queryForMenu(qo);
        return menus;
    }

    @Override
    public List<Menu> getPatentMenus(Long parentId) {
        //定义集合存储菜单
        List<Menu> menus = new ArrayList<>();
        //因为传入的参数id是父菜单的id,所有获取的菜单必定是父菜单信息
        Menu menu = menuMapper.selectByPrimaryKey(parentId);
        //判断获取的菜单是否为空
        while (menu != null) {
            menus.add(menu);//不为空添加到集合中
            //继续获取当前菜单的父菜单
            menu = menu.getParent();
        }
        //逆序
        Collections.reverse(menus);
        return menus;
    }

    private void checkPermission(List<Menu> menus, List<Long> ids) {
        Iterator<Menu> iter = menus.iterator();
        while (iter.hasNext()) {
            Menu menu = iter.next();
            if (!ids.contains(menu.getId())) {
                // 不包含移除
                iter.remove();
                continue;
            }
            List<Menu> children = menu.getChildren();
            if (children.size() > 0) {
                checkPermission(children, ids);
            }
        }
    }



}
